package com.aji.silk1.service.impl;

import com.aji.silk1.domain.Sep;
import com.aji.silk1.domain.dto.SilkDto;
import com.aji.silk1.mapper.SepMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.aji.silk1.domain.Silk;
import com.aji.silk1.service.SilkService;
import com.aji.silk1.mapper.SilkMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Date;

@Service
@RequiredArgsConstructor
public class SilkServiceImpl extends ServiceImpl<SilkMapper, Silk> implements SilkService{

    private final SilkMapper silkMapper;

    private final SepMapper sepMapper;

    @Override
    public void add(SilkDto silkDto) {
        Silk silk = new Silk();
        BeanUtils.copyProperties(silkDto, silk);
        silk.setCreateTime(new Date());

        silkMapper.insert(silk);


        try (
                InputStreamReader isr = new InputStreamReader(silkDto.getFile().getInputStream(), StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr)
        ) {
            String line;
            while ((line = br.readLine()) != null) {
                if (line.trim().isEmpty()) continue;

                String[] parts = line.split(",");
                if (parts.length != 2) {
                    throw new IllegalArgumentException("CSV 文件每行必须是两列，用逗号分隔：" + line);
                }

                try {
                    Double first = Double.parseDouble(parts[0].trim());
                    Double second = Double.parseDouble(parts[1].trim());

                    Sep sep = Sep.builder()
                            .x(first)
                            .y(second)
                            .silkId(silk.getId()).build();

                    sepMapper.insert(sep);
                } catch (NumberFormatException e) {
                    throw new IllegalArgumentException("CSV 中存在非数字内容：" + line);
                }
            }
        } catch (IOException e) {
            throw new RuntimeException("读取 CSV 文件失败", e);
        }
    }
}




